import { getQNToken } from '@/api/updata'
import * as qiniu from 'qiniu-js'
import { computeMD5, fileObj2Arr, showUploadProcess } from '@/utils/upload'
import { addVersion, updateVersions } from '@/api/versions'
import { notification } from 'ant-design-vue'

const upload = {
  state: {
    uploadList: {},
  },
  getters: {
    getUploadList: state => {
      console.log(state.uploadList);
      return state.uploadList
    },
  },
  mutations: {
    SET_UPLOAD_LIST (state, list) {
      state.uploadList = list
    }
  },
  actions: {
    async pushUploadItem ({ commit, state }, { file, success }) {
      // 初始化七牛云上传实例
      const { data } = await getQNToken()
      const uploadKey = await computeMD5(file);
      const observable = qiniu.upload(file, uploadKey, data.data)
      const fileName = file.name
      // 存储上传信息
      // 开始上传
      const sort = Date.now()
      const subscription = observable.subscribe({
        next ({ total }) {
          const { size, loaded } = total
          // 获取上传列表
          const list = state.uploadList
          list[uploadKey] = {
            ...list[uploadKey],
            subscription,
            fileName,
            sort,
            fileSize: size,
            uploadSize: loaded
          }
          commit('SET_UPLOAD_LIST', list)
          showUploadProcess(fileObj2Arr(state.uploadList));
        },
        error (err) {
          console.log("七牛云上传出错，错误信息：", err)
          notification.error({
            message: '错误',
            description: '文件上传失败，请检查网络或文件',
            duration: 0
          })
        },
        async complete ({ key }) {
          // 获取上传列表
          const list = state.uploadList
          list[uploadKey].assetsKey = key
          commit('SET_UPLOAD_LIST', list)
          const uploadData = list[uploadKey]
          if (!!uploadData?.tagNameId) {
            const api = uploadData.id ? updateVersions : addVersion;
            const { data: { status, msg } } = await api({
              ...uploadData,
              resourcesPath: key
            })
            if (status !== 200) {
              file(msg)
              return
            }
          }
          if (typeof success == 'function') {
            success()
          }
        }
      })
    },
    async awaitSubmit({ commit, state }, { key, data }) {
      const list = state.uploadList;
      list[key] = {
        ...list[key],
        ...data,
      };
      commit('SET_UPLOAD_LIST', list)
    },
    cancelUpload({ commit, state }) {
      const list = state.uploadList || {};
      for (const key in list) {
        if (Object.hasOwnProperty.call(list, key)) {
          const element = list[key];
          element?.subscription?.unsubscribe();
        }
      }
      commit('SET_UPLOAD_LIST', {});
    }
  }
}

export default upload
